package com.ilink.groundservice.controller.AiX;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ilink.groundservice.entity.PO.Notebook.AiXNotebook;
import com.ilink.groundservice.entity.PO.Notebook.AiXNotebookAccess;
import com.ilink.groundservice.entity.PO.Notebook.AiXNotebookLike;
import com.ilink.groundservice.entity.PO.Notebook.AiXNotebookShare;
import com.ilink.groundservice.entity.VO.ResponseVO;
import com.ilink.groundservice.service.AiX.AiXNotebookShareService;
import com.ilink.groundservice.service.Notebook.AiXNotebookAccessService;
import com.ilink.groundservice.service.Notebook.AiXNotebookLikeService;
import com.ilink.groundservice.service.Notebook.AiXNotebookService;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * <h3>i-scene</h3>
 *
 * @Description <p></p>
 * @Author yuhe zhu
 * @Date 2025-07-08 14:24
 **/
@Slf4j
@RestController
@RequestMapping("/ground/aix/notebook")
public class AiXNotebookController {
    @Autowired
    private AiXNotebookService aiXNotebookService;
    @Autowired
    private OssService ossService;
    @Autowired
    private AiXNotebookLikeService aiXNotebookLikeService;
    @Autowired
    private AiXNotebookAccessService aiXNotebookAccessService;
    @Autowired
    private AiXNotebookShareService aiXNotebookShareService;

    /**
     * 获取所有笔记
     * @return
     */
    @RequestMapping("/get_all_notebooks")
    public ResponseVO getAllNoteBooks() {
        try {
            List<AiXNotebook> list = aiXNotebookService.list();
            list.forEach(aiXNotebook -> {
                aiXNotebook.setNotebookCover(ossService.getFileUrl(aiXNotebook.getNotebookCover()));
            });
            return ResponseVO.success(list);
        } catch (Exception e) {
             log.error(e.getMessage());
             return ResponseVO.fail(e.getMessage());
        }
    }

    /**
     * 通过id获取
     * @param notebookId
     * @return
     */
    @RequestMapping("/get_notebook_by_id")
    public ResponseVO getNoteBookById(@RequestParam Long notebookId) {
        try {
            AiXNotebook aiXNotebook = aiXNotebookService.getById(notebookId);
            return ResponseVO.success(aiXNotebook);
        } catch (Exception e) {
             log.error(e.getMessage());

             return ResponseVO.fail(e.getMessage());
        }
    }

    /**
     * 新建
     * @param aiXNotebookJson
     * @param cover
     * @return
     */
    @RequestMapping("/insert_notebook")
    public ResponseVO insertNoteBook(@RequestPart("notebook") String aiXNotebookJson  , @RequestPart("cover")MultipartFile cover) {
        try {
            AiXNotebook aiXNotebook = JSON.parseObject(aiXNotebookJson, AiXNotebook.class);
            String cover_url = this.uploadCover(cover);
            aiXNotebook.setNotebookCover(cover_url);
            aiXNotebook.setUserId(UserContext.getUserId());
            boolean result = aiXNotebookService.save(aiXNotebook);
            return ResponseVO.success(result);
        } catch (Exception e) {
             log.error(e.getMessage());
             return ResponseVO.fail(e.getMessage());
        }
    }
    /**
     * 修改
     * @param
     * @param cover
     * @return
     */
    @RequestMapping("/update_notebook")
    public ResponseVO updateNoteBook(@RequestPart("notebook") String notebookJson ,@RequestPart("cover") MultipartFile cover) {
        try {
            AiXNotebook aiXNotebook = JSON.parseObject(notebookJson, AiXNotebook.class);
            if (cover!=null) {
                ossService.deleteFile(aiXNotebook.getNotebookCover());
                String cover_url = this.uploadCover(cover);
                aiXNotebook.setNotebookCover(cover_url);
            }
            aiXNotebookService.updateById(aiXNotebook);
            return ResponseVO.success();
        } catch (Exception e) {
             log.error(e.getMessage());
             return ResponseVO.fail("服务端异常");
        }
    }
    /**
     * 点赞
     * @param notebookId
     * @return
     */
    @PostMapping("/like_notebook")
    public ResponseVO likeNoteBook(@RequestParam Long notebookId) {
        try {
            aiXNotebookService.update()
                    .setSql("like_count = like_count + 1")
                    .eq("notebook_id", notebookId)
                    .update();
            AiXNotebookLike aiXNotebookLike = new AiXNotebookLike();
            aiXNotebookLike.setNotebookId(notebookId);
            aiXNotebookLike.setUserId(UserContext.getUserId());
            aiXNotebookLikeService.save(aiXNotebookLike);
            return ResponseVO.success();
        } catch (Exception e) {
             log.error(e.getMessage());
             return ResponseVO.fail("服务端异常");
        }
    }

    /**
     * 记录访问
     * @param notebookId
     * @return
     */
    @PostMapping("/access_notebook")
    public ResponseVO accessNoteBook(@RequestParam Long notebookId) {
        try {
            aiXNotebookService.update()
                    .setSql("access_count = access_count + 1")
                    .eq("notebook_id", notebookId)
                    .update();
            AiXNotebookAccess aiXNotebookAccess = new AiXNotebookAccess();
            aiXNotebookAccess.setNotebookId(notebookId);
            aiXNotebookAccess.setUserId(UserContext.getUserId());
            aiXNotebookAccessService.save(aiXNotebookAccess);
            return ResponseVO.success();
        } catch (Exception e) {
             log.error(e.getMessage());
             return ResponseVO.fail("服务端异常");
        }
    }
    @PostMapping("/share_notebook")
    public ResponseVO shareNoteBook(@RequestParam Long notebookId) {
        try {
            AiXNotebookShare aiXNotebookShare = new AiXNotebookShare();
            aiXNotebookShare.setNotebookId(notebookId);
            aiXNotebookShare.setUserId(UserContext.getUserId());
            aiXNotebookShareService.save(aiXNotebookShare);
            return ResponseVO.success();
        } catch (Exception e) {
             log.error(e.getMessage());
             return ResponseVO.fail("服务端异常");
        }
    }
    @PostMapping("/delete_notebook")
    public ResponseVO deleteNoteBook(@RequestParam Long notebookId) {
        try {
            aiXNotebookLikeService.remove(new QueryWrapper<AiXNotebookLike>().eq("notebook_id", notebookId));
            aiXNotebookAccessService.remove(new QueryWrapper<AiXNotebookAccess>().eq("notebook_id", notebookId));
            aiXNotebookShareService.remove(new QueryWrapper<AiXNotebookShare>().eq("notebook_id", notebookId));
            aiXNotebookService.removeById(notebookId);
            return ResponseVO.success();
        }catch (Exception e){
            log.error(e.getMessage());
            return ResponseVO.fail("服务端异常");
        }
    }

    /**
     * 操作图片的
     */
    private String uploadCover(MultipartFile image) {
        //魔数检验
        boolean imageByMagicNumber = isImageByMagicNumber(image);
        if (!imageByMagicNumber)  throw new RuntimeException("上传文件并非图片格式");
        String originalFilename = image.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名无效");
        }
        String fileExtension = originalFilename.contains(".")
                ? originalFilename.substring(originalFilename.lastIndexOf("."))
                : "";
        String imageName = UUID.randomUUID() + fileExtension;
        String imagePath = "notebook/cover" + "/";
        if (!ossService.uploadFile(image, imagePath, imageName)) {
            throw new RuntimeException("图片上传失败");
        }
        return imagePath+imageName;
    }

    /**
     * 判断图片格式
     * @param file
     * @return
     */
    private static boolean isImageByMagicNumber(MultipartFile file) {
        if (file == null || file.isEmpty()) return false;

        try (InputStream inputStream = file.getInputStream()) {
            byte[] header = new byte[12]; // 读取前12字节（足够覆盖常见格式）
            if (inputStream.read(header) < header.length) return false;

            // 检查常见图片魔数（PNG/JPEG/GIF/BMP/WEBP）
            return isImageHeader(header);
        } catch (IOException e) {
            return false;
        }
    }

    private static boolean isImageHeader(byte[] header) {
        // PNG: 89 50 4E 47
        boolean isPng = header[0] == (byte) 0x89 && header[1] == 0x50 &&
                header[2] == 0x4E && header[3] == 0x47;

        // JPEG: FF D8
        boolean isJpeg = header[0] == (byte) 0xFF && header[1] == (byte) 0xD8;

        // GIF: "GIF"
        boolean isGif = header[0] == 'G' && header[1] == 'I' && header[2] == 'F';

        // BMP: "BM"
        boolean isBmp = header[0] == 'B' && header[1] == 'M';

        // WEBP: "RIFF" + "WEBP"
        boolean isWebp = header[0] == 'R' && header[1] == 'I' &&
                header[2] == 'F' && header[3] == 'F' &&
                header[8] == 'W' && header[9] == 'E' &&
                header[10] == 'B' && header[11] == 'P';

        return isPng || isJpeg || isGif || isBmp || isWebp;
    }
}
